package com.pureut.quality.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.api.FeignProductionService;
import com.pureut.production.api.domain.dto.QualityTemporaryDto;
import com.pureut.production.api.domain.vo.UpdateByDegreasOutDetailVo;
import com.pureut.production.api.domain.vo.UpdateProductionCheckVo;
import com.pureut.quality.domain.*;
import com.pureut.quality.domain.dto.*;
import com.pureut.quality.domain.vo.MaterialNumberAndBatchNoVo;
import com.pureut.quality.domain.vo.QualityInspectionDocumentVo;
import com.pureut.quality.domain.vo.QualitySchemeConfigurationVo;
import com.pureut.quality.domain.vo.*;
import com.pureut.quality.domain.vo.UpdateQualityStatusVo;
import com.pureut.quality.mapper.*;
import com.pureut.quality.service.*;
import com.pureut.quality.utils.DateCalendarUtils;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.ReturnStatusVo;
import com.pureut.system.api.vo.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 检验单据实现层
 * Author:C
 * Date:2023/02/06 10:29
 * @DESC
 */
@Service
public class QualityInspectionDocumentServiceImpl extends ServiceImpl<QualityInspectionDocumentMapper, QualityInspectionDocument> implements QualityInspectionDocumentService {

    @Resource
    QualityInspectionDocumentMapper qualityInspectionDocumentMapper;

    @Resource
    QualitySchemeConfigurationMapper qualitySchemeConfigurationMapper;

    @Resource
    QualitySchemeConfigurationService qualitySchemeConfigurationService;

    @Resource
    QualitySchemeConfigurationDetailMapper qualitySchemeConfigurationDetailMapper;

    @Resource
    IQualityInspectionService qualityInspectionItemService;

    @Resource
    QualityCheckDocMapper qualityCheckDocMapper;

    @Resource
    QualityTemporaryService qualityTemporaryService;

    @Resource
    FeignService feignService;

    @Resource
    StorageFegin storageFegin;

    @Resource
    FeignProductionService feignProductionService;

    @Resource
    QualityTemporaryMapper qualityTemporaryMapper;

    @Lazy
    @Resource
    QualitySampleInformationService QualitySampleInformationService;

    @Resource
    OrderSupplierManagementMapper orderSupplierManagementMapper;

    @Lazy
    @Resource
    QualityInventoryRecheckMapper qualityInventoryRecheckMapper;

    @Lazy
    @Resource
    QualityInventoryRecheckService qualityInventoryRecheckService;

    /**
     * 检验项目mapper
     */
    @Resource
    QualityInspectionMapper qualityInspectionMapper;

    @Resource
    IQualityInspectionService qualityInspectionService;

    @Resource
    QualityBadSampleService qualityBadSampleService;

    @Resource
    PublicProjectService publicProjectService;

    @Resource
    PublicProjectMapper publicProjectMapper;

    /**
     * 检验单据列表
     *
     * @param qualityInspectionDocumentVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<QualityInspectionDocumentDto> getDocumentList(QualityInspectionDocumentVo qualityInspectionDocumentVo) {
        //检验单据列表
        List<QualityInspectionDocumentDto> list = qualityInspectionDocumentMapper.getList(qualityInspectionDocumentVo);

        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //物料类别
        List<SysDictData> materialCategoryArray = DictUtils.getDictCache("sys_inspection_type");
        Map<String, String> materialCategoryMap = materialCategoryArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //单据状态
        List<SysDictData> documentStatusArray = DictUtils.getDictCache("quality_document_status");
        Map<String, String> documentStatusMap = documentStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //判定等级
        List<SysDictData> judgmentGradeArray = DictUtils.getDictCache("quality_judgment_grade");
        Map<String, String> judgmentGradeMap = judgmentGradeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //检验结果
        List<SysDictData> resultsArray = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> resultsMap = resultsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (QualityInspectionDocumentDto entity : list) {
            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
            qualitySchemeConfigurationVo.setItemRank(Integer.parseInt(entity.getItemRank()));
            qualitySchemeConfigurationVo.setMaterialCode(entity.getMaterialCode());
            qualitySchemeConfigurationVo.setMaterialCategory(entity.getMaterialCategory());
            qualitySchemeConfigurationVo.setCategory(Integer.parseInt(entity.getCategory()));
            qualitySchemeConfigurationVo.setInspectionSheetNo(entity.getInspectionSheetNo());
            //应检数量
            int totalSize = qualityTemporaryService.getTotalSize(qualitySchemeConfigurationVo);
            entity.setQuantityInspected(Long.parseLong(String.valueOf(totalSize)));
//            entity.setQuantityInspected(qualityTemporaryMapper.selectCount(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, entity.getInspectionSheetNo())));
            //检测阶别
            entity.setItemRankDict(rankMap.get(entity.getItemRank()));
            //物料类别
            entity.setCategoryDict(materialCategoryMap.get(entity.getCategory()));
            //单据状态
            entity.setStatusDict(documentStatusMap.get(entity.getStatus()));
            //判定等级
            entity.setJudgmentGradeDict(judgmentGradeMap.get(entity.getJudgmentGrade()));
            //检验结果
            entity.setInspectionResultsDict(resultsMap.get(entity.getInspectionResults()));
            //不良样本数
            List<com.pureut.quality.domain.dto.QualityTemporaryDto> badSampleNumber = qualityTemporaryMapper.getBadSampleNumber(entity.getInspectionSheetNo());
            entity.setBadSampleNum(Long.valueOf(String.valueOf(badSampleNumber.size())));
        }
        return list;
    }

    /**
     * 检验单据新增
     *
     * @param qualityInspectionDocumentVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(QualityInspectionDocumentVo qualityInspectionDocumentVo) throws Exception {

        QualityInspectionDocument qualityInspectionDocument = new QualityInspectionDocument();
        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        qualityInspectionDocument.setItemRank(qualityInspectionDocumentVo.getItemRank());
        if (qualityInspectionDocumentVo.getInspectionSheetNo() == null) {
            String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:testbill:list");
            if (authorityCoding == null) {
                throw new GlobalException("该单据未进行配置，无法生成单据编码");
            }
            String itemRankDict = rankMap.get(String.valueOf(qualityInspectionDocumentVo.getItemRank()));
            qualityInspectionDocument.setInspectionSheetNo(itemRankDict + "-" + authorityCoding);
        } else {
            qualityInspectionDocument.setInspectionSheetNo(qualityInspectionDocumentVo.getInspectionSheetNo());
        }
        qualityInspectionDocument.setCategory(qualityInspectionDocumentVo.getCategory())
                .setModeType(qualityInspectionDocumentVo.getModeType())
                .setMaterialCategory(qualityInspectionDocumentVo.getMaterialCategory())
                .setProductionLine(qualityInspectionDocumentVo.getProductionLine())
                .setStatus(1)
//                .setJudgmentGrade(1)
                .setInspectDept(qualityInspectionDocumentVo.getInspectDept())
                .setMaterialCode(qualityInspectionDocumentVo.getMaterialCode())
                .setBatchNo(qualityInspectionDocumentVo.getBatchNo())
                .setAssociatedNo(qualityInspectionDocumentVo.getAssociatedNo())
                .setOnlyMark(qualityInspectionDocumentVo.getOnlyMark())
                .setDifferentString(qualityInspectionDocumentVo.getDifferentString())
                .setCreateBy(SecurityUtils.getUsername())
                .setCreateTime(new Date())
                .setClasses(qualityInspectionDocumentVo.getClasses())
                .setGroupCode(qualityInspectionDocumentVo.getGroupCode())
                .setCrossSkyTime(qualityInspectionDocumentVo.getCrossSkyTime())
                .setInspectDept(qualityInspectionDocumentVo.getInspectDept())
                .setDeptId(SecurityUtils.getDeptId());
        //获取检验方案配置列表
        List<QualitySchemeConfiguration> list = qualitySchemeConfigurationService.list();
        boolean isTrue = false;
        boolean isCateGory = false;
        for (QualitySchemeConfiguration entity : list) {
            //同一检测阶别、类别、生产阶别、物料类别/物料编码下只允许存在一条检测方案；(物料优先)
            //阶别
            boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
            //类别
            boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
            //物料编码
            boolean a4 = entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode());

//            boolean isItemRank =  && ;
//            if (isItemRank) {
            //判断编码是否匹配
            if (a1 && a2 && a4 && entity.getSchemeType() == 2) {
                //判断抽样方式
                if (entity.getSamplingMethod() == 1) {
                    //如果是固定值
                    qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                } else {
                    //如果不是固定值就是百分比
                    BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                    BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                    BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
                    long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                    qualityInspectionDocument.setQuantityInspected(l);
                }
                isTrue = true;
                //将对应的检验方案添加进公共项目表
                List<PublicProject> publicProjectList = new ArrayList<>();
                Long id = entity.getId();
                //根据检验方案id获取对应的检验项目编码
                List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                    PublicProject publicProject = new PublicProject();
                    //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                    QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                    publicProject.setItemCode(qualityInspection.getItemCode())
                            .setItemName(qualityInspection.getItemName())
                            .setItemRank(qualityInspection.getItemRank())
                            .setMaterialType(qualityInspection.getMaterialType())
                            .setItemControlMode(qualityInspection.getItemControlMode())
                            .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                            .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                            .setItemUnit(qualityInspection.getItemUnit())
                            .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                            .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                            .setItemCheckContent(qualityInspection.getItemCheckContent())
                            .setIsAverage(qualityInspection.getIsAverage())
                            .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                            .setCreateTime(new Date());
                    publicProjectList.add(publicProject);
                }
                publicProjectService.saveBatch(publicProjectList);
                break;
            }
        }
        if (!isTrue) {
            for (QualitySchemeConfiguration entity : list) {
                //阶别
                boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                //类别
                boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                //物料类别
                boolean a3 = entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory();

                if (a1 && a2 && a3 && entity.getSchemeType() == 1) {
                    //判断物料类别是否匹配
                    //判断抽样方式
                    if (entity.getSamplingMethod() == 1) {
                        //如果是固定值
                        qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                    } else {
                        //如果不是固定值就是百分比
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                        BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
                        long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                        qualityInspectionDocument.setQuantityInspected(l);
                    }
                    isCateGory = true;
                    //将对应的检验方案添加进公共项目表
                    List<PublicProject> publicProjectList = new ArrayList<>();
                    Long id = entity.getId();
                    //根据检验方案id获取对应的检验项目编码
                    List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                    for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                        PublicProject publicProject = new PublicProject();
                        //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                        QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                        publicProject.setItemCode(qualityInspection.getItemCode())
                                .setItemName(qualityInspection.getItemName())
                                .setItemRank(qualityInspection.getItemRank())
                                .setMaterialType(qualityInspection.getMaterialType())
                                .setItemControlMode(qualityInspection.getItemControlMode())
                                .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                .setItemUnit(qualityInspection.getItemUnit())
                                .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                .setItemCheckContent(qualityInspection.getItemCheckContent())
                                .setIsAverage(qualityInspection.getIsAverage())
                                .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                .setCreateTime(new Date());
                        publicProjectList.add(publicProject);
                    }
                    publicProjectService.saveBatch(publicProjectList);
                    break;
                }
//            }
//            }
            }
        }

        if (!isTrue && !isCateGory) {
            throw new GlobalException("没有进行对应配置，无法生成检验单");
        }
        save(qualityInspectionDocument);
        //插入检验单据数据存储表
        List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoList = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();

        List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
        for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNoList) {
            QualityTemporary qualityTemporary = new QualityTemporary();
            qualityTemporary.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
            qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
            qualityTemporary.setBatchNo(entity.getBatchNo());
            qualityTemporary.setMaterialCode(qualityInspectionDocument.getMaterialCode());
            qualityTemporary.setInspectionMark(2);
            qualityTemporaryList.add(qualityTemporary);
        }
        return qualityTemporaryService.saveBatch(qualityTemporaryList);
    }

    /**
     * 检验单据新增（脱脂模块使用）
     *
     * @param qualityInspectionDocumentVo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDegreas(QualityInspectionDocumentVo qualityInspectionDocumentVo) throws Exception {
        QualityInspectionDocument qualityInspectionDocument = new QualityInspectionDocument();
        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据批次号及脱脂制令单号获取品质检验单
        QualityInspectionDocument qualityInspectionDocumentByDegreas = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda()
                .eq(QualityInspectionDocument::getBatchNo, qualityInspectionDocumentVo.getBatchNo())
                .eq(QualityInspectionDocument::getAssociatedNo, qualityInspectionDocumentVo.getAssociatedNo()));
        if (qualityInspectionDocumentByDegreas == null) {
            qualityInspectionDocument.setItemRank(qualityInspectionDocumentVo.getItemRank());
            if (qualityInspectionDocumentVo.getInspectionSheetNo() == null) {
                String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:testbill:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                String itemRankDict = rankMap.get(String.valueOf(qualityInspectionDocumentVo.getItemRank()));
                qualityInspectionDocument.setInspectionSheetNo(itemRankDict + "-" + authorityCoding);
            } else {
                qualityInspectionDocument.setInspectionSheetNo(qualityInspectionDocumentVo.getInspectionSheetNo());
            }
            qualityInspectionDocument.setCategory(qualityInspectionDocumentVo.getCategory())
                    .setModeType(qualityInspectionDocumentVo.getModeType())
                    .setMaterialCategory(qualityInspectionDocumentVo.getMaterialCategory())
                    .setProductionLine(qualityInspectionDocumentVo.getProductionLine())
                    .setStatus(1)
//                .setJudgmentGrade(1)
                    .setMaterialCode(qualityInspectionDocumentVo.getMaterialCode())
                    .setBatchNo(qualityInspectionDocumentVo.getBatchNo())
                    .setAssociatedNo(qualityInspectionDocumentVo.getAssociatedNo())
                    .setDifferentString(qualityInspectionDocumentVo.getDifferentString())
                    .setCreateBy(SecurityUtils.getUsername())
                    .setCreateTime(new Date())
                    .setClasses(qualityInspectionDocumentVo.getClasses())
                    .setCrossSkyTime(qualityInspectionDocumentVo.getCrossSkyTime())
                    .setInspectDept(qualityInspectionDocumentVo.getInspectDept())
                    .setDeptId(SecurityUtils.getDeptId());
            //应检数量判断
            List<QualitySchemeConfiguration> list = qualitySchemeConfigurationService.list();
            boolean isTrue = false;
            boolean isCateGory = false;
            for (QualitySchemeConfiguration entity : list) {

                //同一检测阶别、类别、生产阶别、物料类别/物料编码下只允许存在一条检测方案；(物料优先)
                //阶别
                boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                //类别
                boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                //物料编码
                boolean a4 = entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode());

                //判断编码是否匹配
                if (a1 && a2 && a4 && entity.getSchemeType() == 2) {
                    //判断抽样方式
                    if (entity.getSamplingMethod() == 1) {
                        //如果是固定值
                        qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                    } else {
                        //如果不是固定值就是百分比
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                        BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
                        long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                        qualityInspectionDocument.setQuantityInspected(l);
                    }
                    isTrue = true;
                    //将对应的检验方案添加进公共项目表
                    List<PublicProject> publicProjectList = new ArrayList<>();
                    Long id = entity.getId();
                    //根据检验方案id获取对应的检验项目编码
                    List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                    for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                        PublicProject publicProject = new PublicProject();
                        //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                        QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                        publicProject.setItemCode(qualityInspection.getItemCode())
                                .setItemName(qualityInspection.getItemName())
                                .setItemRank(qualityInspection.getItemRank())
                                .setMaterialType(qualityInspection.getMaterialType())
                                .setItemControlMode(qualityInspection.getItemControlMode())
                                .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                .setItemUnit(qualityInspection.getItemUnit())
                                .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                .setItemCheckContent(qualityInspection.getItemCheckContent())
                                .setIsAverage(qualityInspection.getIsAverage())
                                .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                .setCreateTime(new Date());
                        publicProjectList.add(publicProject);
                    }
                    publicProjectService.saveBatch(publicProjectList);
                    break;
                }
            }
            if (!isTrue) {
                for (QualitySchemeConfiguration entity : list) {
                    //阶别
                    boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                    //类别
                    boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                    //物料类别
                    boolean a3 = entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory();

                    if (a1 && a2 && a3 && entity.getSchemeType() == 1) {
                        //判断物料类别是否匹配
                        //判断抽样方式
                        if (entity.getSamplingMethod() == 1) {
                            //如果是固定值
                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                        } else {
                            //如果不是固定值就是百分比
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                            qualityInspectionDocument.setQuantityInspected(l);
                        }
                        isCateGory = true;
                        //将对应的检验方案添加进公共项目表
                        List<PublicProject> publicProjectList = new ArrayList<>();
                        Long id = entity.getId();
                        //根据检验方案id获取对应的检验项目编码
                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                            PublicProject publicProject = new PublicProject();
                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                            publicProject.setItemCode(qualityInspection.getItemCode())
                                    .setItemName(qualityInspection.getItemName())
                                    .setItemRank(qualityInspection.getItemRank())
                                    .setMaterialType(qualityInspection.getMaterialType())
                                    .setItemControlMode(qualityInspection.getItemControlMode())
                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                    .setItemUnit(qualityInspection.getItemUnit())
                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
                                    .setIsAverage(qualityInspection.getIsAverage())
                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                    .setCreateTime(new Date());
                            publicProjectList.add(publicProject);
                        }
                        publicProjectService.saveBatch(publicProjectList);
                        break;
                    }
//            }
//            }
                }
            }
//                //检测阶别、类别是否匹配
//                boolean isItemRank = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank() && entity.getCategory() == qualityInspectionDocumentVo.getCategory();
//                if (isItemRank) {
//                    //判断编码是否匹配
//                    if (entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode()) && entity.getSchemeType() == 2) {
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    }
//                    if (entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory() && entity.getSchemeType() == 1) {
//                        //判断物料类别是否匹配
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    }
//                }
//            }
            if (!isTrue && !isCateGory) {
                throw new GlobalException("没有进行对应配置，无法生成检验单");
            }
            save(qualityInspectionDocument);
            //插入检验单据数据存储表
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoList = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();

            List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNoList) {
                QualityTemporary qualityTemporary = new QualityTemporary();
                qualityTemporary.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
                qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityTemporary.setBatchNo(entity.getBatchNo());
                qualityTemporary.setMaterialCode(qualityInspectionDocument.getMaterialCode());
                qualityTemporary.setInspectionMark(2);
                qualityTemporaryList.add(qualityTemporary);
            }
            return qualityTemporaryService.saveBatch(qualityTemporaryList);
        }
        //如果送检的批次和已经存在的检验单批次相同，且没有进行检验，就不重新生成品质检验单，只将物料进行添加
        if (qualityInspectionDocumentByDegreas.getBatchNo().equals(qualityInspectionDocumentVo.getBatchNo()) && qualityInspectionDocumentByDegreas.getStatus() == 1) {
            //就将无聊添加进该品质检验单
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();
            List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNo) {
                QualityTemporary qualityTemporary = new QualityTemporary();
                qualityTemporary.setInspectionSheetNo(qualityInspectionDocumentByDegreas.getInspectionSheetNo());
                qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityTemporary.setBatchNo(entity.getBatchNo());
                qualityTemporary.setMaterialCode(qualityInspectionDocumentByDegreas.getMaterialCode());
                qualityTemporary.setInspectionMark(2);
                qualityTemporaryList.add(qualityTemporary);
            }
            return qualityTemporaryService.saveBatch(qualityTemporaryList);
        }
        //不相等，就重新生成品质检验单
        boolean b = qualityInspectionDocumentByDegreas.getBatchNo().equals(qualityInspectionDocumentVo.getBatchNo());
        if (!b) {
            qualityInspectionDocument.setItemRank(qualityInspectionDocumentVo.getItemRank());
            if (qualityInspectionDocumentVo.getInspectionSheetNo() == null) {
                String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:testbill:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                String itemRankDict = rankMap.get(String.valueOf(qualityInspectionDocumentVo.getItemRank()));
                qualityInspectionDocument.setInspectionSheetNo(itemRankDict + "-" + authorityCoding);
            } else {
                qualityInspectionDocument.setInspectionSheetNo(qualityInspectionDocumentVo.getInspectionSheetNo());
            }
            qualityInspectionDocument.setCategory(qualityInspectionDocumentVo.getCategory())
                    .setModeType(qualityInspectionDocumentVo.getModeType())
                    .setMaterialCategory(qualityInspectionDocumentVo.getMaterialCategory())
                    .setProductionLine(qualityInspectionDocumentVo.getProductionLine())
                    .setStatus(1)
//                .setJudgmentGrade(1)
                    .setMaterialCode(qualityInspectionDocumentVo.getMaterialCode())
                    .setBatchNo(qualityInspectionDocumentVo.getBatchNo())
                    .setAssociatedNo(qualityInspectionDocumentVo.getAssociatedNo())
                    .setDifferentString(qualityInspectionDocumentVo.getDifferentString())
                    .setCreateBy(SecurityUtils.getUsername())
                    .setCreateTime(new Date())
                    .setClasses(qualityInspectionDocumentVo.getClasses())
                    .setCrossSkyTime(qualityInspectionDocumentVo.getCrossSkyTime())
                    .setDeptId(SecurityUtils.getDeptId());
            //应检数量判断
            List<QualitySchemeConfiguration> list = qualitySchemeConfigurationService.list();
            boolean isTrue = false;
            boolean isCateGory = false;
            for (QualitySchemeConfiguration entity : list) {

                //同一检测阶别、类别、生产阶别、物料类别/物料编码下只允许存在一条检测方案；(物料优先)
                //阶别
                boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                //类别
                boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                //物料编码
                boolean a4 = entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode());

                //判断编码是否匹配
                if (a1 && a2 && a4 && entity.getSchemeType() == 2) {
                    //判断抽样方式
                    if (entity.getSamplingMethod() == 1) {
                        //如果是固定值
                        qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                    } else {
                        //如果不是固定值就是百分比
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                        BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
                        long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                        qualityInspectionDocument.setQuantityInspected(l);
                    }
                    isTrue = true;
                    //将对应的检验方案添加进公共项目表
                    List<PublicProject> publicProjectList = new ArrayList<>();
                    Long id = entity.getId();
                    //根据检验方案id获取对应的检验项目编码
                    List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                    for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                        PublicProject publicProject = new PublicProject();
                        //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                        QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                        publicProject.setItemCode(qualityInspection.getItemCode())
                                .setItemName(qualityInspection.getItemName())
                                .setItemRank(qualityInspection.getItemRank())
                                .setMaterialType(qualityInspection.getMaterialType())
                                .setItemControlMode(qualityInspection.getItemControlMode())
                                .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                .setItemUnit(qualityInspection.getItemUnit())
                                .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                .setItemCheckContent(qualityInspection.getItemCheckContent())
                                .setIsAverage(qualityInspection.getIsAverage())
                                .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                .setCreateTime(new Date());
                        publicProjectList.add(publicProject);
                    }
                    publicProjectService.saveBatch(publicProjectList);
                    break;
                }
            }
            if (!isTrue) {
                for (QualitySchemeConfiguration entity : list) {
                    //阶别
                    boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                    //类别
                    boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                    //物料类别
                    boolean a3 = entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory();

                    if (a1 && a2 && a3 && entity.getSchemeType() == 1) {
                        //判断物料类别是否匹配
                        //判断抽样方式
                        if (entity.getSamplingMethod() == 1) {
                            //如果是固定值
                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                        } else {
                            //如果不是固定值就是百分比
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                            qualityInspectionDocument.setQuantityInspected(l);
                        }
                        isCateGory = true;
                        //将对应的检验方案添加进公共项目表
                        List<PublicProject> publicProjectList = new ArrayList<>();
                        Long id = entity.getId();
                        //根据检验方案id获取对应的检验项目编码
                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                            PublicProject publicProject = new PublicProject();
                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                            publicProject.setItemCode(qualityInspection.getItemCode())
                                    .setItemName(qualityInspection.getItemName())
                                    .setItemRank(qualityInspection.getItemRank())
                                    .setMaterialType(qualityInspection.getMaterialType())
                                    .setItemControlMode(qualityInspection.getItemControlMode())
                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                    .setItemUnit(qualityInspection.getItemUnit())
                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
                                    .setIsAverage(qualityInspection.getIsAverage())
                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                    .setCreateTime(new Date());
                            publicProjectList.add(publicProject);
                        }
                        publicProjectService.saveBatch(publicProjectList);
                        break;
                    }
//            }
//            }
                }
            }
//            for (QualitySchemeConfiguration entity : list) {
//                //检测阶别、类别是否匹配
//                boolean isItemRank = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank() && entity.getCategory() == qualityInspectionDocumentVo.getCategory();
//                if (isItemRank) {
//                    //判断编码是否匹配
//                    if (entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode()) && entity.getSchemeType() == 2) {
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    } else if (entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory() && entity.getSchemeType() == 1) {
//                        //判断物料类别是否匹配
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    }
//                }
//            }
//            if (!isTrue) {
//                throw new GlobalException("没有进行对应配置，无法生成检验单");
//            }
            if (!isTrue && !isCateGory) {
                throw new GlobalException("没有进行对应配置，无法生成检验单");
            }
            save(qualityInspectionDocument);
            //插入检验单据数据存储表
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoList = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();

            List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNoList) {
                QualityTemporary qualityTemporary = new QualityTemporary();
                qualityTemporary.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
                qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityTemporary.setBatchNo(entity.getBatchNo());
                qualityTemporary.setMaterialCode(qualityInspectionDocument.getMaterialCode());
                qualityTemporary.setInspectionMark(2);
                qualityTemporaryList.add(qualityTemporary);
            }
            return qualityTemporaryService.saveBatch(qualityTemporaryList);
        }
        return false;
    }

    /**
     * 检验单据新增(仓库模块使用)
     *
     * @param qualityInspectionDocumentVo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWares(QualityInspectionDocumentVo qualityInspectionDocumentVo) throws Exception {
        QualityInspectionDocument qualityInspectionDocument = new QualityInspectionDocument();
        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //根据关联号获取品质检验单
        QualityInspectionDocument qualityInspectionDocumentByDegreas = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getAssociatedNo, qualityInspectionDocumentVo.getAssociatedNo()));
        if (qualityInspectionDocumentByDegreas == null) {
            qualityInspectionDocument.setItemRank(qualityInspectionDocumentVo.getItemRank());
            if (qualityInspectionDocumentVo.getInspectionSheetNo() == null) {
                String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:testbill:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                String itemRankDict = rankMap.get(String.valueOf(qualityInspectionDocumentVo.getItemRank()));
                qualityInspectionDocument.setInspectionSheetNo(itemRankDict + "-" + authorityCoding);
            } else {
                qualityInspectionDocument.setInspectionSheetNo(qualityInspectionDocumentVo.getInspectionSheetNo());
            }
            qualityInspectionDocument.setCategory(qualityInspectionDocumentVo.getCategory())
                    .setModeType(qualityInspectionDocumentVo.getModeType())
                    .setMaterialCategory(qualityInspectionDocumentVo.getMaterialCategory())
                    .setProductionLine(qualityInspectionDocumentVo.getProductionLine())
                    .setStatus(1)
//                .setJudgmentGrade(1)
                    .setMaterialCode(qualityInspectionDocumentVo.getMaterialCode())
                    .setBatchNo(qualityInspectionDocumentVo.getBatchNo())
                    .setAssociatedNo(qualityInspectionDocumentVo.getAssociatedNo())
                    .setDifferentString(qualityInspectionDocumentVo.getDifferentString())
                    .setCreateBy(SecurityUtils.getUsername())
                    .setCreateTime(new Date())
                    .setClasses(qualityInspectionDocumentVo.getClasses())
                    .setCrossSkyTime(qualityInspectionDocumentVo.getCrossSkyTime())
                    .setInspectDept(qualityInspectionDocumentVo.getInspectDept())
                    .setDeptId(SecurityUtils.getDeptId());
            //应检数量判断
            List<QualitySchemeConfiguration> list = qualitySchemeConfigurationService.list();
            boolean isTrue = false;
            boolean isCateGory = false;
            for (QualitySchemeConfiguration entity : list) {
                //同一检测阶别、类别、生产阶别、物料类别/物料编码下只允许存在一条检测方案；(物料优先)
                //阶别
                boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                //类别
                boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                //物料编码
                boolean a4 = entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode());

//            boolean isItemRank =  && ;
//            if (isItemRank) {
                //判断编码是否匹配
                if (a1 && a2 && a4 && entity.getSchemeType() == 2) {
                    //判断抽样方式
                    if (entity.getSamplingMethod() == 1) {
                        //如果是固定值
                        qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                    } else {
                        //如果不是固定值就是百分比
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                        BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
                        long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                        qualityInspectionDocument.setQuantityInspected(l);
                    }
                    isTrue = true;
                    //将对应的检验方案添加进公共项目表
                    List<PublicProject> publicProjectList = new ArrayList<>();
                    Long id = entity.getId();
                    //根据检验方案id获取对应的检验项目编码
                    List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                    for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                        PublicProject publicProject = new PublicProject();
                        //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                        QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                        publicProject.setItemCode(qualityInspection.getItemCode())
                                .setItemName(qualityInspection.getItemName())
                                .setItemRank(qualityInspection.getItemRank())
                                .setMaterialType(qualityInspection.getMaterialType())
                                .setItemControlMode(qualityInspection.getItemControlMode())
                                .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                .setItemUnit(qualityInspection.getItemUnit())
                                .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                .setItemCheckContent(qualityInspection.getItemCheckContent())
                                .setIsAverage(qualityInspection.getIsAverage())
                                .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                .setCreateTime(new Date());
                        publicProjectList.add(publicProject);
                    }
                    publicProjectService.saveBatch(publicProjectList);
                    break;
                }
            }
            if (!isTrue) {
                for (QualitySchemeConfiguration entity : list) {
                    //阶别
                    boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                    //类别
                    boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                    //物料类别
                    boolean a3 = entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory();

                    if (a1 && a2 && a3 && entity.getSchemeType() == 1) {
                        //判断物料类别是否匹配
                        //判断抽样方式
                        if (entity.getSamplingMethod() == 1) {
                            //如果是固定值
                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                        } else {
                            //如果不是固定值就是百分比
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                            qualityInspectionDocument.setQuantityInspected(l);
                        }
                        isCateGory = true;
                        //将对应的检验方案添加进公共项目表
                        List<PublicProject> publicProjectList = new ArrayList<>();
                        Long id = entity.getId();
                        //根据检验方案id获取对应的检验项目编码
                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                            PublicProject publicProject = new PublicProject();
                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                            publicProject.setItemCode(qualityInspection.getItemCode())
                                    .setItemName(qualityInspection.getItemName())
                                    .setItemRank(qualityInspection.getItemRank())
                                    .setMaterialType(qualityInspection.getMaterialType())
                                    .setItemControlMode(qualityInspection.getItemControlMode())
                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                    .setItemUnit(qualityInspection.getItemUnit())
                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
                                    .setIsAverage(qualityInspection.getIsAverage())
                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                    .setCreateTime(new Date());
                            publicProjectList.add(publicProject);
                        }
                        publicProjectService.saveBatch(publicProjectList);
                        break;
                    }
//            }
//            }
                }
            }

            if (!isTrue && !isCateGory) {
                throw new GlobalException("没有进行对应配置，无法生成检验单");
            }
//            for (QualitySchemeConfiguration entity : list) {
//                //检测阶别、类别是否匹配
//                boolean isItemRank = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank() && entity.getCategory() == qualityInspectionDocumentVo.getCategory();
//                if (isItemRank) {
//                    //判断编码是否匹配
//                    if (entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode()) && entity.getSchemeType() == 2) {
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    } else if (entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory() && entity.getSchemeType() == 1) {
//                        //判断物料类别是否匹配
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    }
//                }
//            }
//            if (!isTrue) {
//                throw new GlobalException("没有进行对应配置，无法生成检验单");
//            }
            save(qualityInspectionDocument);
            //插入检验单据数据存储表
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoList = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();

            List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNoList) {
                QualityTemporary qualityTemporary = new QualityTemporary();
                qualityTemporary.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
                qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityTemporary.setBatchNo(entity.getBatchNo());
                qualityTemporary.setMaterialCode(qualityInspectionDocument.getMaterialCode());
                qualityTemporary.setInspectionMark(2);
                qualityTemporaryList.add(qualityTemporary);
            }
            return qualityTemporaryService.saveBatch(qualityTemporaryList);
        }

        //如果送检的关联单号和已经存在的检验单关联单号相同，且没有进行检验，就不重新生成品质检验单，只将物料进行添加
        if (qualityInspectionDocumentByDegreas.getAssociatedNo().equals(qualityInspectionDocumentVo.getAssociatedNo()) && qualityInspectionDocumentByDegreas.getStatus() == 1) {
            //就将物料添加进该品质检验单
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();
            List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNo) {
                QualityTemporary qualityTemporary = new QualityTemporary();
                qualityTemporary.setInspectionSheetNo(qualityInspectionDocumentByDegreas.getInspectionSheetNo());
                qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityTemporary.setBatchNo(entity.getBatchNo());
                qualityTemporary.setMaterialCode(qualityInspectionDocumentByDegreas.getMaterialCode());
                qualityTemporary.setInspectionMark(2);
                qualityTemporaryList.add(qualityTemporary);
            }
            return qualityTemporaryService.saveBatch(qualityTemporaryList);
        }

        //不相等，就重新生成品质检验单
        boolean b = qualityInspectionDocumentByDegreas.getAssociatedNo().equals(qualityInspectionDocumentVo.getAssociatedNo());
        if (!b) {
            qualityInspectionDocument.setItemRank(qualityInspectionDocumentVo.getItemRank());
            if (qualityInspectionDocumentVo.getInspectionSheetNo() == null) {
                String authorityCoding = feignService.getAuthorityCoding("quality:inspecmanage:testbill:list");
                if (authorityCoding == null) {
                    throw new GlobalException("该单据未进行配置，无法生成单据编码");
                }
                String itemRankDict = rankMap.get(String.valueOf(qualityInspectionDocumentVo.getItemRank()));
                qualityInspectionDocument.setInspectionSheetNo(itemRankDict + "-" + authorityCoding);
            } else {
                qualityInspectionDocument.setInspectionSheetNo(qualityInspectionDocumentVo.getInspectionSheetNo());
            }
            qualityInspectionDocument.setCategory(qualityInspectionDocumentVo.getCategory())
                    .setModeType(qualityInspectionDocumentVo.getModeType())
                    .setMaterialCategory(qualityInspectionDocumentVo.getMaterialCategory())
                    .setProductionLine(qualityInspectionDocumentVo.getProductionLine())
                    .setStatus(1)
//                .setJudgmentGrade(1)
                    .setMaterialCode(qualityInspectionDocumentVo.getMaterialCode())
                    .setBatchNo(qualityInspectionDocumentVo.getBatchNo())
                    .setAssociatedNo(qualityInspectionDocumentVo.getAssociatedNo())
                    .setDifferentString(qualityInspectionDocumentVo.getDifferentString())
                    .setCreateBy(SecurityUtils.getUsername())
                    .setCreateTime(new Date())
                    .setClasses(qualityInspectionDocumentVo.getClasses())
                    .setCrossSkyTime(qualityInspectionDocumentVo.getCrossSkyTime())
                    .setDeptId(SecurityUtils.getDeptId());
            //应检数量判断
            List<QualitySchemeConfiguration> list = qualitySchemeConfigurationService.list();
            boolean isTrue = false;
            boolean isCateGory = false;
            for (QualitySchemeConfiguration entity : list) {
                //同一检测阶别、类别、生产阶别、物料类别/物料编码下只允许存在一条检测方案；(物料优先)
                //阶别
                boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                //类别
                boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                //物料编码
                boolean a4 = entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode());

//            boolean isItemRank =  && ;
//            if (isItemRank) {
                //判断编码是否匹配
                if (a1 && a2 && a4 && entity.getSchemeType() == 2) {
                    //判断抽样方式
                    if (entity.getSamplingMethod() == 1) {
                        //如果是固定值
                        qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                    } else {
                        //如果不是固定值就是百分比
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                        BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
                        long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                        qualityInspectionDocument.setQuantityInspected(l);
                    }
                    isTrue = true;
                    //将对应的检验方案添加进公共项目表
                    List<PublicProject> publicProjectList = new ArrayList<>();
                    Long id = entity.getId();
                    //根据检验方案id获取对应的检验项目编码
                    List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                    for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                        PublicProject publicProject = new PublicProject();
                        //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                        QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                        publicProject.setItemCode(qualityInspection.getItemCode())
                                .setItemName(qualityInspection.getItemName())
                                .setItemRank(qualityInspection.getItemRank())
                                .setMaterialType(qualityInspection.getMaterialType())
                                .setItemControlMode(qualityInspection.getItemControlMode())
                                .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                .setItemUnit(qualityInspection.getItemUnit())
                                .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                .setItemCheckContent(qualityInspection.getItemCheckContent())
                                .setIsAverage(qualityInspection.getIsAverage())
                                .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                .setCreateTime(new Date());
                        publicProjectList.add(publicProject);
                    }
                    publicProjectService.saveBatch(publicProjectList);
                    break;
                }
            }
            if (!isTrue) {
                for (QualitySchemeConfiguration entity : list) {
                    //阶别
                    boolean a1 = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank();
                    //类别
                    boolean a2 = entity.getCategory() == qualityInspectionDocumentVo.getCategory();
                    //物料类别
                    boolean a3 = entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory();

                    if (a1 && a2 && a3 && entity.getSchemeType() == 1) {
                        //判断物料类别是否匹配
                        //判断抽样方式
                        if (entity.getSamplingMethod() == 1) {
                            //如果是固定值
                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
                        } else {
                            //如果不是固定值就是百分比
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
                            qualityInspectionDocument.setQuantityInspected(l);
                        }
                        isCateGory = true;
                        //将对应的检验方案添加进公共项目表
                        List<PublicProject> publicProjectList = new ArrayList<>();
                        Long id = entity.getId();
                        //根据检验方案id获取对应的检验项目编码
                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
                            PublicProject publicProject = new PublicProject();
                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
                            publicProject.setItemCode(qualityInspection.getItemCode())
                                    .setItemName(qualityInspection.getItemName())
                                    .setItemRank(qualityInspection.getItemRank())
                                    .setMaterialType(qualityInspection.getMaterialType())
                                    .setItemControlMode(qualityInspection.getItemControlMode())
                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
                                    .setItemUnit(qualityInspection.getItemUnit())
                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
                                    .setIsAverage(qualityInspection.getIsAverage())
                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
                                    .setCreateTime(new Date());
                            publicProjectList.add(publicProject);
                        }
                        publicProjectService.saveBatch(publicProjectList);
                        break;
                    }
//            }
//            }
                }
            }

            if (!isTrue && !isCateGory) {
                throw new GlobalException("没有进行对应配置，无法生成检验单");
            }
//            for (QualitySchemeConfiguration entity : list) {
//                //检测阶别、类别是否匹配
//                boolean isItemRank = entity.getItemRank() == qualityInspectionDocumentVo.getItemRank() && entity.getCategory() == qualityInspectionDocumentVo.getCategory();
//                if (isItemRank) {
//                    //判断编码是否匹配
//                    if (entity.getMaterialCode().equals(qualityInspectionDocumentVo.getMaterialCode()) && entity.getSchemeType() == 2) {
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 1);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    } else if (entity.getMaterialCategory() == qualityInspectionDocumentVo.getMaterialCategory() && entity.getSchemeType() == 1) {
//                        //判断物料类别是否匹配
//                        //判断抽样方式
//                        if (entity.getSamplingMethod() == 1) {
//                            //如果是固定值
//                            qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size())));
//                        } else {
//                            //如果不是固定值就是百分比
//                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(qualityInspectionDocumentVo.getMaterialNumberAndBatchNo().size()));
//                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(entity.getSamplingNum()));
//                            BigDecimal divide = bigDecimal.divide(bigDecimal1, 0);
//                            long l = Long.parseLong(divide.multiply(BigDecimal.valueOf(100)).toString());
//                            qualityInspectionDocument.setQuantityInspected(l);
//                        }
//                        isTrue = true;
//                        //将对应的检验方案添加进公共项目表
//                        List<PublicProject> publicProjectList = new ArrayList<>();
//                        Long id = entity.getId();
//                        //根据检验方案id获取对应的检验项目编码
//                        List<QualitySchemeConfigurationDetail> qualitySchemeConfigurationDetails = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().eq(QualitySchemeConfigurationDetail::getSchemeId, id));
//                        for (QualitySchemeConfigurationDetail configurationDetail : qualitySchemeConfigurationDetails) {
//                            PublicProject publicProject = new PublicProject();
//                            //通过检验编码获取检验项目相关数据，并和检验单据进行绑定
//                            QualityInspection qualityInspection = qualityInspectionMapper.selectOne(new QueryWrapper<QualityInspection>().lambda().eq(QualityInspection::getItemCode, configurationDetail.getProjectCode()));
//                            publicProject.setItemCode(qualityInspection.getItemCode())
//                                    .setItemName(qualityInspection.getItemName())
//                                    .setItemRank(qualityInspection.getItemRank())
//                                    .setMaterialType(qualityInspection.getMaterialType())
//                                    .setItemControlMode(qualityInspection.getItemControlMode())
//                                    .setItemUpperLimit(configurationDetail.getUpperLimitValue())
//                                    .setItemLowerLimit(configurationDetail.getLowerLimitValue())
//                                    .setItemUnit(qualityInspection.getItemUnit())
//                                    .setItemSampleNumber(qualityInspection.getItemSampleNumber())
//                                    .setItemDetectionMode(qualityInspection.getItemDetectionMode())
//                                    .setItemCheckContent(qualityInspection.getItemCheckContent())
//                                    .setIsAverage(qualityInspection.getIsAverage())
//                                    .setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo())
//                                    .setCreateTime(new Date());
//                            publicProjectList.add(publicProject);
//                        }
//                        publicProjectService.saveBatch(publicProjectList);
//                        break;
//                    }
//                }
//            }
//            if (!isTrue) {
//                throw new GlobalException("没有进行对应配置，无法生成检验单");
//            }
            save(qualityInspectionDocument);
            //插入检验单据数据存储表
            List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNoList = qualityInspectionDocumentVo.getMaterialNumberAndBatchNo();

            List<QualityTemporary> qualityTemporaryList = new ArrayList<>();
            for (MaterialNumberAndBatchNoVo entity : materialNumberAndBatchNoList) {
                QualityTemporary qualityTemporary = new QualityTemporary();
                qualityTemporary.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
                qualityTemporary.setMaterialNumber(entity.getMaterialNumber());
                qualityTemporary.setBatchNo(entity.getBatchNo());
                qualityTemporary.setMaterialCode(qualityInspectionDocument.getMaterialCode());
                qualityTemporary.setInspectionMark(2);
                qualityTemporaryList.add(qualityTemporary);
            }
            return qualityTemporaryService.saveBatch(qualityTemporaryList);
        }
        return false;
    }

    /**
     * 单据信息查看
     *
     * @param id
     * @return
     */
    @Override
    public QualityInspectionDocumentDto getView(Long id) {
        QualityInspectionDocumentDto qualityInspectionDocumentMapperViewById = qualityInspectionDocumentMapper.getViewById(id);
        //检测阶别
        List<SysDictData> rankArray = DictUtils.getDictCache("item_rank");
        Map<String, String> rankMap = rankArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //物料类别
        List<SysDictData> materialCategoryArray = DictUtils.getDictCache("sys_inspection_type");
        Map<String, String> materialCategoryMap = materialCategoryArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //单据状态
        List<SysDictData> documentStatusArray = DictUtils.getDictCache("quality_document_status");
        Map<String, String> documentStatusMap = documentStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //判定等级
        List<SysDictData> judgmentGradeArray = DictUtils.getDictCache("quality_judgment_grade");
        Map<String, String> judgmentGradeMap = judgmentGradeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //检验结果
        List<SysDictData> resultsArray = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> resultsMap = resultsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
        qualitySchemeConfigurationVo.setItemRank(Integer.parseInt(qualityInspectionDocumentMapperViewById.getItemRank()));
        qualitySchemeConfigurationVo.setMaterialCode(qualityInspectionDocumentMapperViewById.getMaterialCode());
        qualitySchemeConfigurationVo.setMaterialCategory(qualityInspectionDocumentMapperViewById.getMaterialCategory());
        qualitySchemeConfigurationVo.setCategory(Integer.parseInt(qualityInspectionDocumentMapperViewById.getCategory()));
        qualitySchemeConfigurationVo.setInspectionSheetNo(qualityInspectionDocumentMapperViewById.getInspectionSheetNo());
        //应检数量
        int totalSize = qualityTemporaryService.getTotalSize(qualitySchemeConfigurationVo);
        qualityInspectionDocumentMapperViewById.setQuantityInspected(Long.parseLong(String.valueOf(totalSize)));
        //不良样本数
        List<com.pureut.quality.domain.dto.QualityTemporaryDto> badSampleNumber = qualityTemporaryMapper.getBadSampleNumber(qualityInspectionDocumentMapperViewById.getInspectionSheetNo());
        qualityInspectionDocumentMapperViewById.setBadSampleNum(Long.parseLong(String.valueOf(badSampleNumber.size())));
        //检测阶别
        qualityInspectionDocumentMapperViewById.setItemRankDict(rankMap.get(qualityInspectionDocumentMapperViewById.getItemRank()));
        //物料类别
        qualityInspectionDocumentMapperViewById.setCategoryDict(materialCategoryMap.get(qualityInspectionDocumentMapperViewById.getCategory()));
        //单据状态
        qualityInspectionDocumentMapperViewById.setStatusDict(documentStatusMap.get(qualityInspectionDocumentMapperViewById.getStatus()));
        //判定等级
        qualityInspectionDocumentMapperViewById.setJudgmentGradeDict(judgmentGradeMap.get(qualityInspectionDocumentMapperViewById.getJudgmentGrade()));
        //检验结果
        qualityInspectionDocumentMapperViewById.setInspectionResultsDict(resultsMap.get(qualityInspectionDocumentMapperViewById.getInspectionResults()));
        return qualityInspectionDocumentMapperViewById;
    }

    /**
     * 样品检验(检验项目列表)
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    public List<SampleInspectionDto> sampleInspection(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {
//        List<QualitySchemeConfigurationDetail> details = null;
//        //根据阶别、类别、方案类型、物料编码查询检验项目
//        Long byCodeIds = qualitySchemeConfigurationMapper.getConfigurationListByCode(qualitySchemeConfigurationVo);
//        if (byCodeIds != null) {
//            //获取该id下的明细
//            details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getSchemeId, byCodeIds));
//        } else {
//            //根据阶别、类别、方案类型、物料类别查询检验项目
//            Long byCategoryIds = qualitySchemeConfigurationMapper.getConfigurationListByCategory(qualitySchemeConfigurationVo);
//            if (byCategoryIds != null) {
//                //获取该id下的明细
//                details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getSchemeId, byCategoryIds));
//            }
//        }
        //获取检验单号
        List<QualityInspectionDocument> qualityInspectionDocuments;
        if (qualitySchemeConfigurationVo.getOrderNumber() != null) {
            qualityInspectionDocuments = qualityInspectionDocumentMapper.selectList(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getAssociatedNo, qualitySchemeConfigurationVo.getOrderNumber()));

        } else {
            qualityInspectionDocuments = qualityInspectionDocumentMapper.selectList(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getInspectionSheetNo, qualitySchemeConfigurationVo.getInspectionSheetNo()));
        }
        List<PublicProject> publicProjectList = null;

        if (qualityInspectionDocuments.size() > 0) {
            QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocuments.get(0);
            publicProjectList = publicProjectMapper.selectList(new QueryWrapper<PublicProject>().lambda().eq(PublicProject::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));

        }
//        else {
//            throw new GlobalException("未查询到对应的检验单据");
//        }

        if (publicProjectList == null) {
            throw new GlobalException("没有查询到对应的检验项目");
        }
        //获取单据配置信息
        QualityCheckDoc qualityCheckDoc = qualityCheckDocMapper.selectOne(new QueryWrapper<QualityCheckDoc>().lambda().eq(QualityCheckDoc::getItemRank, qualitySchemeConfigurationVo.getItemRank()).eq(QualityCheckDoc::getMaterialType, qualitySchemeConfigurationVo.getCategory()));
        if (qualityCheckDoc == null) {
            throw new GlobalException("没有配置单据信息!");
        }

        List<SampleInspectionDto> sampleInspectionDtoList = new ArrayList<>();

        //管控方式
        List<SysDictData> controlModeArray = DictUtils.getDictCache("quality_item_control_mode");
        Map<String, String> controlModeMap = controlModeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        for (PublicProject entity : publicProjectList) {
            //获取检验项目
//            QualityInspection byId = qualityInspectionItemService.getById(entity.getInspectionId());
            SampleInspectionDto sampleInspectionDto = new SampleInspectionDto();
            sampleInspectionDto.setItemName(entity.getItemName())
                    .setItemCode(entity.getItemCode())
                    .setItemDetectionMode(String.valueOf(entity.getItemDetectionMode()))
                    .setItemCheckContent(entity.getItemCheckContent())
                    .setItemControlMode(String.valueOf(entity.getItemControlMode()))
                    .setItemControlModeDict(controlModeMap.get(String.valueOf(entity.getItemControlMode())))
                    .setItemUnit(entity.getItemUnit())
                    .setItemLowerLimit(entity.getItemLowerLimit())
                    .setItemUpperLimit(entity.getItemUpperLimit())
                    .setId(entity.getItemId())
                    .setIsAverage(entity.getIsAverage())
                    .setCheckDecisionMode(qualityCheckDoc.getCheckDecisionMode());
            //获取样本个数
            int itemSampleNumber = entity.getItemSampleNumber();
            List<ActualValueVo> actualValueList = new ArrayList<>();
            for (int i = 1; i <= itemSampleNumber; i++) {
                ActualValueVo actualValueVo = new ActualValueVo();
                actualValueList.add(actualValueVo);
            }
            sampleInspectionDto.setActualValueList(actualValueList);

            sampleInspectionDtoList.add(sampleInspectionDto);

        }

        return sampleInspectionDtoList;
    }

    /**
     * 来料处理
     *
     * @param processingIncomingMaterialsVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processingIncomingMaterials(ProcessingIncomingMaterialsVo processingIncomingMaterialsVo) {

        //获取检验单信息
        QualityInspectionDocument qualityInspectionDocument = getById(processingIncomingMaterialsVo.getId());
        if (qualityInspectionDocument.getItemRank() != 1) {
            throw new GlobalException("只能对检测级别为“IQC”的单据进行来料处理");
        }
        if (qualityInspectionDocument.getStatus() != 6) {
            throw new GlobalException("只能对“待处理”状态的单据进行此操作");
        }
        //回传库存复检单据状态
        QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, qualityInspectionDocument.getAssociatedNo()));
        if (qualityInventoryRecheck != null) {
            qualityInventoryRecheck.setStatus(7);
            qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
            //修改该复检单据下的物料在仓库中的物料等级和状态
            List<QualityTemporary> qualityTemporaries = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
            List<String> materialNumberList = new ArrayList<>();

            for (QualityTemporary qualityTemporary : qualityTemporaries) {
                materialNumberList.add(qualityTemporary.getMaterialNumber());
            }
            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
            warehouseStatusUpdateVo.setStatusValue(2);
            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
            warehouseStatusUpdateVo.setMaterialGradeValue(processingIncomingMaterialsVo.getIncomingJudgmentGrade());
            storageFegin.getUpdate(warehouseStatusUpdateVo);
        }
        //判断判定等级,如果是批退
        if (processingIncomingMaterialsVo.getIncomingJudgmentGrade() == 1) {
            List<String> materialNumberList = new ArrayList<>();
            List<PickingPurchaseDetailVo> purchaseDetailVoList = new ArrayList<>();
            //根据检验单号获取该批物料信息
            List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
            for (QualityTemporary entity : qualityTemporaryList) {
                PickingPurchaseDetailVo pickingPurchaseDetailVo = new PickingPurchaseDetailVo();
                pickingPurchaseDetailVo.setPdoductNumber(entity.getMaterialNumber());
                pickingPurchaseDetailVo.setItemNum("1");
                pickingPurchaseDetailVo.setBatchNumber(entity.getBatchNo());
                pickingPurchaseDetailVo.setItemCode(entity.getMaterialCode());
                pickingPurchaseDetailVo.setOutgoingNumber(1);
                pickingPurchaseDetailVo.setDepositor(SecurityUtils.getUsername());
                pickingPurchaseDetailVo.setDeliveryTime(new Date());
                purchaseDetailVoList.add(pickingPurchaseDetailVo);

                entity.setJudgmentGrade(2);
                materialNumberList.add(entity.getMaterialNumber());
            }
            qualityTemporaryService.updateBatchById(qualityTemporaryList);
            //同时修改检验单据判定等级为批退
            qualityInspectionDocument.setJudgmentGrade(2);
            //回传仓库物料数据状态
            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
            warehouseStatusUpdateVo.setStatusValue(2);
            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
            int incomingJudgmentGrade = processingIncomingMaterialsVo.getIncomingJudgmentGrade();
            if (incomingJudgmentGrade == 1) {
                warehouseStatusUpdateVo.setMaterialGradeValue(2);
            }
            storageFegin.getUpdate(warehouseStatusUpdateVo);
            // 在来料打印页面对应的号码全部删除，上表的打印状态更新为“已完成”
            DeleteDetailVo deleteDetailVo = new DeleteDetailVo();
            deleteDetailVo.setMaterialNumberList(materialNumberList);
            AjaxResult ajaxResult = storageFegin.deleteDetail(deleteDetailVo);
            String code = ajaxResult.get("code").toString();
            if ("200".equals(code)) {
                // 同时生成一条状态为“已完成”的采购退货单
                PickingPurchaseVo pickingPurchaseVo = new PickingPurchaseVo();
                pickingPurchaseVo.setTransceiverType(1);
                pickingPurchaseVo.setMaterialCode(qualityInspectionDocument.getMaterialCode());
                pickingPurchaseVo.setList(purchaseDetailVoList);
                //通过唯一标识获取入库单号
                if (qualityInspectionDocument.getModeType() == 10) {
//                    String onlyMark = qualityInspectionDocument.getAssociatedNo();
//                    String receiptNo = storageFegin.getReceiptNo(onlyMark);
                    pickingPurchaseVo.setConnectionId(qualityInspectionDocument.getAssociatedNo());
                    //fegin调用获取供应商id
//                    String supplierNum = qualityInspectionDocument.getDifferentString();
//                    if (supplierNum != null) {
//                        OrderSupplierManagementDto orderSupplierData = orderSupplierManagementMapper.getOrderSupplierData(supplierNum);
//                        pickingPurchaseVo.setSupplierId(orderSupplierData.getId());
//                    }
                }
//                AjaxResult ajaxResult1 = storageFegin.addPurchaseFeign(pickingPurchaseVo);
//                String data = ajaxResult1.get("code").toString();
//                if ("200".equals(data)) {
                qualityInspectionDocument.setStatus(7);
                return updateById(qualityInspectionDocument);
//                }
            }
        }
        //判断判定等级,如果是让步接收
        if (processingIncomingMaterialsVo.getIncomingJudgmentGrade() == 2) {
//            List<String> materialNumberList = new ArrayList<>();
            //根据检验单号获取该批物料信息
            List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
            for (QualityTemporary entity : qualityTemporaryList) {
                entity.setJudgmentGrade(1);
//                materialNumberList.add(entity.getMaterialNumber());
            }
            qualityTemporaryService.updateBatchById(qualityTemporaryList);
            //同时修改检验单据判定等级为良品
            qualityInspectionDocument.setJudgmentGrade(1);
            //修改检验单据状态为已完成
            qualityInspectionDocument.setStatus(7);
            //修改来料打印页面状态为待打印
            String batchNumber = qualityTemporaryList.get(0).getBatchNo();

            UpdatePrintStatusVo updatePrintStatusVo = new UpdatePrintStatusVo();
            updatePrintStatusVo.setBatchNumber(batchNumber);
            storageFegin.updatePrintStatus(updatePrintStatusVo);

            return updateById(qualityInspectionDocument);


            //库存状态更新为“在库”
//            UpdateStatusVo updateStatusVo = new UpdateStatusVo();
//            updateStatusVo.setMaterialNumberList(materialNumberList);
//            AjaxResult ajaxResult = storageFegin.updateStatus(updateStatusVo);
//            String data = ajaxResult.get("code").toString();
//            if ("200".equals(data)) {
//                return updateById(qualityInspectionDocument);
//            }else {
//                throw new GlobalException("未获取到相关物料");
//            }
        }

        //判断判定等级,如果是部分接收
        if (processingIncomingMaterialsVo.getIncomingJudgmentGrade() == 3) {

            List<String> ids = Arrays.asList(processingIncomingMaterialsVo.getIds().split(","));
            if (ids.size() < 1) {
                throw new GlobalException("请至少勾选一条数据");
            }
            List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().in(QualityTemporary::getId, ids));
            //勾选的部分物料等级标记为“良品"
            List<PickingPurchaseDetailVo> purchaseDetailVoList = new ArrayList<>();
            List<String> materialNumberList = new ArrayList<>();
            for (QualityTemporary entity : qualityTemporaryList) {
                PickingPurchaseDetailVo pickingPurchaseDetailVo = new PickingPurchaseDetailVo();
                pickingPurchaseDetailVo.setPdoductNumber(entity.getMaterialNumber());
                pickingPurchaseDetailVo.setItemNum("1");
                pickingPurchaseDetailVo.setBatchNumber(entity.getBatchNo());
                pickingPurchaseDetailVo.setItemCode(entity.getMaterialCode());
                pickingPurchaseDetailVo.setOutgoingNumber(1);
                pickingPurchaseDetailVo.setDepositor(SecurityUtils.getUsername());
                pickingPurchaseDetailVo.setDeliveryTime(new Date());
                purchaseDetailVoList.add(pickingPurchaseDetailVo);

                entity.setJudgmentGrade(1);
                materialNumberList.add(entity.getMaterialNumber());
            }
            qualityTemporaryService.updateBatchById(qualityTemporaryList);
            //修改来料打印页面状态为待打印
            String batchNumber = qualityTemporaryList.get(0).getBatchNo();
            UpdatePrintStatusVo updatePrintStatusVo = new UpdatePrintStatusVo();
            updatePrintStatusVo.setBatchNumber(batchNumber);
            storageFegin.updatePrintStatus(updatePrintStatusVo);

            //同时生成一条状态为“已完成”的采购退货单
//            PickingPurchaseVo pickingPurchaseVo = new PickingPurchaseVo();
//            pickingPurchaseVo.setTransceiverType(1);
//            pickingPurchaseVo.setMaterialCode(qualityInspectionDocument.getMaterialCode());
//            pickingPurchaseVo.setList(purchaseDetailVoList);
//            AjaxResult ajaxResult1 = storageFegin.addPurchaseFeign(pickingPurchaseVo);
//            String code1 = ajaxResult1.get("code").toString();
//            if ("200".equals(code1)) {
            //未勾选的部分，在来料打印页面对应的号码删除
            List<String> materialList = new ArrayList<>();
            List<QualityTemporary> allList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()).notIn(QualityTemporary::getId, ids));
            for (QualityTemporary entity : allList) {
                materialList.add(entity.getMaterialNumber());
            }
            DeleteDetailVo deleteDetailVo = new DeleteDetailVo();
            deleteDetailVo.setMaterialNumberList(materialList);
            storageFegin.deleteData(deleteDetailVo);

            qualityInspectionDocument.setStatus(7);
            qualityInspectionDocument.setJudgmentGrade(5);
            return updateById(qualityInspectionDocument);

//            }
        }
        return false;
    }

    /**
     * 品质处理
     *
     * @param processingIncomingMaterialsVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean qualityTreatment(ProcessingIncomingMaterialsVo processingIncomingMaterialsVo) throws Exception {
        //获取检验单信息
        QualityInspectionDocument qualityInspectionDocument = getById(processingIncomingMaterialsVo.getId());
        if (qualityInspectionDocument.getItemRank() == 1) {
            throw new GlobalException("不能对检测级别为“IQC”的单据进行品质处理");
        }
        if (qualityInspectionDocument.getStatus() != 6) {
            throw new GlobalException("只能对“待处理”状态的单据进行此操作");
        }
        List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));

        if (processingIncomingMaterialsVo.getIncomingJudgmentGrade() == 1) {
            for (QualityTemporary entity : qualityTemporaryList) {
                entity.setJudgmentGrade(3);
            }
        } else {
            for (QualityTemporary entity : qualityTemporaryList) {
                entity.setJudgmentGrade(4);
            }
        }
        //品质处理回传状态
        ReturnStatusVo returnStatusVo = new ReturnStatusVo();
        returnStatusVo.setModeType(qualityInspectionDocument.getModeType());
        returnStatusVo.setAssociatedNo(qualityInspectionDocument.getAssociatedNo());
        if (processingIncomingMaterialsVo.getIncomingJudgmentGrade() == 1) {
            returnStatusVo.setJudgmentGrade(3);
        } else {
            returnStatusVo.setJudgmentGrade(4);
        }
        returnStatusVo.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
        returnStatusVo.setBatchNum(qualityInspectionDocument.getBatchNo());
        //feign调用修改对应模块状态及数据
        returnQualityStatus(returnStatusVo);

        qualityInspectionDocument.setJudgmentGrade(processingIncomingMaterialsVo.getIncomingJudgmentGrade());
        qualityInspectionDocument.setStatus(7);
        updateById(qualityInspectionDocument);
        //回传库存复检单据状态
        QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, qualityInspectionDocument.getAssociatedNo()));
        if (qualityInventoryRecheck != null) {
            qualityInventoryRecheck.setStatus(7);
            qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
            //修改该复检单据下的物料在仓库中的物料等级和状态
            List<QualityTemporary> qualityTemporaries = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
            List<String> materialNumberList = new ArrayList<>();

            for (QualityTemporary qualityTemporary : qualityTemporaries) {
                materialNumberList.add(qualityTemporary.getMaterialNumber());
            }
            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
            warehouseStatusUpdateVo.setStatusValue(2);
            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
            warehouseStatusUpdateVo.setMaterialGradeValue(processingIncomingMaterialsVo.getIncomingJudgmentGrade());
            storageFegin.getUpdate(warehouseStatusUpdateVo);
        }

        //水刺回传物料等级
        if (qualityInspectionDocument.getModeType() == 9) {
            UpdateProductionCheckVo updateProductionCheckVo = new UpdateProductionCheckVo();
            updateProductionCheckVo.setGrade(String.valueOf(qualityInspectionDocument.getJudgmentGrade()));
            updateProductionCheckVo.setQualityDoc(qualityInspectionDocument.getInspectionSheetNo());
            updateProductionCheckVo.setDocNum(qualityInspectionDocument.getAssociatedNo());
            feignProductionService.spunlaceUpdateGrade(updateProductionCheckVo);
        }

        //脱脂回传物料等级
        if (qualityInspectionDocument.getModeType() == 20) {
            UpdateByDegreasOutDetailVo updateByDegreasOutDetailVo = new UpdateByDegreasOutDetailVo();
            updateByDegreasOutDetailVo.setMaterialLevel(qualityInspectionDocument.getJudgmentGrade());
            updateByDegreasOutDetailVo.setDegreasOrderNumber(qualityInspectionDocument.getAssociatedNo());
            updateByDegreasOutDetailVo.setBatchNumber(qualityInspectionDocument.getBatchNo());
            feignProductionService.updateByDegreasOutDetailQuality(updateByDegreasOutDetailVo);
        }
        return qualityTemporaryService.updateBatchById(qualityTemporaryList);
    }

    /**
     * 批量审核
     *
     * @param orderBatchReviewVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAudit(OrderBatchReviewVo orderBatchReviewVo) throws Exception {

        List<String> ids = Arrays.asList(orderBatchReviewVo.getIds().split(","));

        if (ids.size() < 1) {
            throw new GlobalException("请至少勾选一条数据进行审核");
        }
        List<QualityInspectionDocument> qualityInspectionDocuments = qualityInspectionDocumentMapper.selectList(new QueryWrapper<QualityInspectionDocument>().lambda().in(QualityInspectionDocument::getId, ids));

        List<QualityInspectionDocument> collect = qualityInspectionDocuments.stream().filter(entity -> entity.getStatus() == 3 || entity.getStatus() == 4).collect(Collectors.toList());
        if (collect.size() < 1) {
            throw new GlobalException("勾选中包含非待审核和审核中的数据");
        }

        for (QualityInspectionDocument entity : qualityInspectionDocuments) {
            if (entity.getStatus() == 3 || entity.getStatus() == 4) {
                String perms = "quality:inspecmanage:testbill:batchAudit";
                int isAdopt = orderBatchReviewVo.getIsAdopt();
                String auditDoc = entity.getInspectionSheetNo();
                String auditRemarks = orderBatchReviewVo.getReviewComments();
                Long userId = SecurityUtils.getUserId();
                AjaxResult sequence = feignService.getSequenceTwo(perms, 4, isAdopt, auditRemarks, auditDoc, userId);
                Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
                if (data == null) {
                    throw new GlobalException("未对该审核进行配置");
                }
                if (orderBatchReviewVo.getIsAdopt() == 1) {
                    //同意审核
                    if (data == 1) {
                        if (entity.getInspectionResults() == 1) {
                            entity.setStatus(7);
                            //保存平均值，并将数据进行回传
                            ReturnStatusVo returnStatusVo = new ReturnStatusVo();
                            List<ResultMaterialVo> resultMaterialVoList = new ArrayList<>();
                            BigDecimal divide1 = new BigDecimal(0);
                            if (entity.getModeType() == 10 || entity.getModeType() == 11) {
                                //获取样本结果数据
                                List<SampleInspectionDto> list = QualitySampleInformationService.getList(entity.getInspectionSheetNo());
                                Map<Long, List<SampleInspectionDto>> materialGroup = list.stream().collect(Collectors.groupingBy(SampleInspectionDto::getItemId));


                                //平均皮重
                                BigDecimal divideAvg = new BigDecimal(0);
                                for (Map.Entry<Long, List<SampleInspectionDto>> materialGroupEntity : materialGroup.entrySet()) {

                                    List<SampleInspectionDto> value = materialGroupEntity.getValue();
                                    BigDecimal bigDecimal = new BigDecimal(0);

                                    for (SampleInspectionDto sample : value) {
                                        //将同组的平均值相加
                                        if (sample.getAverageValue() != null && !"null".equals(sample.getAverageValue())) {
                                            bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(sample.getAverageValue())));
                                        }
                                    }
                                    divideAvg = divideAvg.add(bigDecimal.divide(new BigDecimal(value.size()), 0));
                                }
                                divide1 = divideAvg.divide(new BigDecimal(String.valueOf(materialGroup.size())), 0);

                                Map<String, List<SampleInspectionDto>> collect1 = list.stream().collect(Collectors.groupingBy(SampleInspectionDto::getSampleNumber));
                                for (Map.Entry<String, List<SampleInspectionDto>> materialGroupEntity : collect1.entrySet()) {
                                    ResultMaterialVo resultMaterialVo = new ResultMaterialVo();
                                    resultMaterialVo.setMaterialNumber(materialGroupEntity.getKey());
                                    // TODO //根据样本号码判断该物料的检验项目是不是勾选了皮重，如果勾选就传皮重，如果不是就不传
//                                resultMaterialVo.setAverageTare(divide1.toString());
                                    resultMaterialVo.setAverageTare("0");
                                    resultMaterialVoList.add(resultMaterialVo);
                                }
                            }
                            returnStatusVo.setModeType(entity.getModeType());
                            returnStatusVo.setAssociatedNo(entity.getAssociatedNo());
                            returnStatusVo.setOnlyMark(entity.getOnlyMark());
                            returnStatusVo.setMaterialList(resultMaterialVoList);
                            returnStatusVo.setInspectionSheetNo(entity.getInspectionSheetNo());
                            returnStatusVo.setBatchNum(entity.getBatchNo());
                            //feign调用修改对应模块状态及数据
                            boolean b = returnStatus(returnStatusVo);
                            if (b) {
                                entity.setAverageTare(divide1.toString());
                            } else {
                                throw new GlobalException("feign调用失败");
                            }
                        } else {
                            entity.setStatus(6);
                        }
                        UpdateProductionCheckVo updateProductionCheckVo = new UpdateProductionCheckVo();
                        updateProductionCheckVo.setDocNum(entity.getAssociatedNo());
                        updateProductionCheckVo.setQualityDoc(entity.getInspectionSheetNo());
                        updateProductionCheckVo.setQualityStatus(String.valueOf(entity.getStatus()));
                        updateProductionCheckVo.setResult(String.valueOf(entity.getInspectionResults()));
                        if (entity.getStatus() == 6) {
                            updateProductionCheckVo.setType("2");
                        }
                        if (entity.getStatus() == 7) {
                            updateProductionCheckVo.setType("1");
                        }
                        try {
                            feignProductionService.spunlaceUpdateStatus(updateProductionCheckVo);
                        } catch (Exception e) {
                            throw new GlobalException("feign调用失败");
                        }

                        entity.setReviewComments(orderBatchReviewVo.getReviewComments());
                        //回传库存复检单据状态
                        QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, entity.getAssociatedNo()));
                        if (qualityInventoryRecheck != null) {
                            qualityInventoryRecheck.setStatus(entity.getStatus());
                            qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
                            //修改该复检单据下的物料在仓库中的物料等级和状态
                            List<QualityTemporary> qualityTemporaries = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, entity.getInspectionSheetNo()));
                            List<String> materialNumberList = new ArrayList<>();

                            for (QualityTemporary qualityTemporary : qualityTemporaries) {
                                materialNumberList.add(qualityTemporary.getMaterialNumber());
                            }
                            WarehouseStatusUpdateVo warehouseStatusUpdateVo = new WarehouseStatusUpdateVo();
                            warehouseStatusUpdateVo.setStatusValue(2);
                            warehouseStatusUpdateVo.setMaterialNumberList(materialNumberList);
                            warehouseStatusUpdateVo.setMaterialGradeValue(1);
                            storageFegin.getUpdate(warehouseStatusUpdateVo);
                        }

                        feignService.updateStatus(3, auditDoc, "检验单据");
                        return updateById(entity);
                    } else if (data == 2) {
                        entity.setStatus(4);
                        entity.setReviewComments(orderBatchReviewVo.getReviewComments());
                        //回传库存复检单据状态
                        QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, entity.getAssociatedNo()));
                        if (qualityInventoryRecheck != null) {
                            qualityInventoryRecheck.setStatus(entity.getStatus());
                            qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
                        }
                        return updateById(entity);
                    } else if (data == 3) {
                        throw new GlobalException("没有审核权限");
                    } else {
                        throw new GlobalException("该用户已经审核过");
                    }
                } else {
                    if (data == 1 || data == 2) {
                        entity.setStatus(5);
                        UpdateProductionCheckVo updateProductionCheckVo = new UpdateProductionCheckVo();
                        updateProductionCheckVo.setDocNum(entity.getAssociatedNo());
                        updateProductionCheckVo.setQualityDoc(entity.getInspectionSheetNo());
                        updateProductionCheckVo.setQualityStatus(String.valueOf(entity.getStatus()));
                        updateProductionCheckVo.setResult(String.valueOf(entity.getInspectionResults()));
                        updateProductionCheckVo.setType("2");
                        try {
                            feignProductionService.spunlaceUpdateStatus(updateProductionCheckVo);
                        } catch (Exception e) {
                            throw new GlobalException("feign调用失败");
                        }
                        entity.setReviewComments(orderBatchReviewVo.getReviewComments());
                        //回传库存复检单据状态
                        QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, entity.getAssociatedNo()));
                        if (qualityInventoryRecheck != null) {
                            qualityInventoryRecheck.setStatus(entity.getStatus());
                            qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
                        }

                        //新增审核代办
                        SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

                        sysWorkbenchAuditAgentVo.setDocConfig("quality:inspecmanage:testbill:batchAudit");
                        sysWorkbenchAuditAgentVo.setReceiptName("检验单据");
                        sysWorkbenchAuditAgentVo.setReceiptNumber(auditDoc);//
                        sysWorkbenchAuditAgentVo.setStatus(2);//待处理
                        sysWorkbenchAuditAgentVo.setReceiptContent("有单据未通过,请及时查看");
                        sysWorkbenchAuditAgentVo.setPassFlag("1");
                        sysWorkbenchAuditAgentVo.setCreateName(entity.getCreateBy());


                        feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                        return updateById(entity);
                    } else if (data == 3) {
                        throw new GlobalException("没有审核权限");
                    } else {
                        throw new GlobalException("该用户已经审核过");
                    }
                }
            } else {
                throw new GlobalException("只能对“待审核、审核中”状态的单据进行此操作");
            }
        }

        return true;
    }

    /**
     * 各模块回传检验状态
     *
     * @param returnStatusVo
     * @return
     */
    @Override
    public boolean returnStatus(ReturnStatusVo returnStatusVo) throws Exception {


        //生产领料：1
        if (returnStatusVo.getModeType() == 1) {
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.updateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 2) {
            //委外发货 2
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.outSourceUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 3) {
            //销售发货：3
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.saleUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 4) {
            //返工出库：4
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.competeUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 5) {
            //采购退货：5
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.purchaseUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 6) {
            //委外退货：6
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.returnUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 7) {
            //其他出库：7
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.restUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 8) {
            //调拨管理：8
            UpdateDocVo updateDocVo = new UpdateDocVo();
            updateDocVo.setDocNum(returnStatusVo.getAssociatedNo());
            AjaxResult ajaxResult = storageFegin.allotUpdateStatus(updateDocVo);
            String code = ajaxResult.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 9) {
            //水刺产出：9
        } else if (returnStatusVo.getModeType() == 10) {
            //采购打印：10
            AjaxResult dataByOnlyMark = storageFegin.getDataByOnlyMark(returnStatusVo);
            String code = dataByOnlyMark.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 11) {
            //委外打印：11
            AjaxResult dataByOnlyMark = storageFegin.getDataByOnlyMarkSub(returnStatusVo);
            String code = dataByOnlyMark.get("code").toString();
            return "200".equals(code);
        } else if (returnStatusVo.getModeType() == 20) {
            //脱脂产出明细数据回传:20
            List<QualityTemporaryDto> list = qualityTemporaryMapper.getListCopy(returnStatusVo.getInspectionSheetNo());
            for (QualityTemporaryDto entity : list) {
                entity.setJudgmentGrade("1");
                entity.setInspectionResults("1");
            }
            UpdateByDegreasOutDetailVo updateByDegreasOutDetailVo = new UpdateByDegreasOutDetailVo();
            updateByDegreasOutDetailVo.setList(list);
            updateByDegreasOutDetailVo.setDegreasOrderNumber(returnStatusVo.getAssociatedNo());
            updateByDegreasOutDetailVo.setBatchNumber(returnStatusVo.getBatchNum());
            updateByDegreasOutDetailVo.setMaterialLevel(1);
            feignProductionService.updateByDegreasOutDetail(updateByDegreasOutDetailVo);
        } else if (returnStatusVo.getModeType() == 12) {
            //销售退货明细数据回传:12
            UpdateStatusByQualityVo updateStatusByQualityVo = new UpdateStatusByQualityVo();
            updateStatusByQualityVo.setAssociatedNo(returnStatusVo.getAssociatedNo());
            storageFegin.updateStatusByQuality(updateStatusByQualityVo);
        } else if (returnStatusVo.getModeType() == 13) {
            //生产退料
            UpdateStatusByQualityVo updateStatusByQualityVo = new UpdateStatusByQualityVo();
            updateStatusByQualityVo.setAssociatedNo(returnStatusVo.getAssociatedNo());
            storageFegin.updateProductionMaterialByQuality(updateStatusByQualityVo);
        } else if (returnStatusVo.getModeType() == 15) {
            //完工入库
            UpdateStatusByQualityVo updateStatusByQualityVo = new UpdateStatusByQualityVo();
            updateStatusByQualityVo.setAssociatedNo(returnStatusVo.getAssociatedNo());
            storageFegin.updatewipCompletionByQuality(updateStatusByQualityVo);
        } else if (returnStatusVo.getModeType() == 14) {
            //其他入库
            UpdateStatusByQualityVo updateStatusByQualityVo = new UpdateStatusByQualityVo();
            updateStatusByQualityVo.setAssociatedNo(returnStatusVo.getAssociatedNo());
            storageFegin.updateMiscellaneousReceiptByQuality(updateStatusByQualityVo);
        }

        return true;
    }

    /**
     * 各模块回传检验状态(品质处理时调用)
     *
     * @param returnStatusVo
     * @return
     */
    @Override
    public boolean returnQualityStatus(ReturnStatusVo returnStatusVo) throws Exception {

        if (returnStatusVo.getModeType() == 15) {
            //完工入库
            storageFegin.wipCompletionQualityStatus(returnStatusVo);
        }
        return true;
    }

    /**
     * 删除品质检验单
     *
     * @param relevanceDoc
     * @return
     */
    @Override
    public boolean removeDoc(String relevanceDoc) {

        //查询当前单据下的品质检验单
        List<QualityInspectionDocument> qualityInspectionDocuments = qualityInspectionDocumentMapper.selectList(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getAssociatedNo, relevanceDoc));

        for (QualityInspectionDocument qualityInspectionDocument : qualityInspectionDocuments) {
            qualityBadSampleService.remove(new QueryWrapper<QualityBadSample>().lambda().eq(QualityBadSample::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
            QualitySampleInformationService.remove(new QueryWrapper<QualitySampleInformation>().lambda().eq(QualitySampleInformation::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
            qualityTemporaryService.remove(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
        }

        boolean remove = remove(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getAssociatedNo, relevanceDoc));
        return remove;
    }

    /**
     * 生产看板-近7天良品率
     *
     * @param lineCode
     * @return
     */
    @Override
    public YieldDto getYield(String lineCode) {

        YieldDto yieldDto = new YieldDto();

        //获取当前时间之前的7天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        ArrayList<String> arrayList = DateCalendarUtils.pastDay(format);
        //7天时间
        yieldDto.setDateList(arrayList);
        List<GroupYieldDto> groupYieldDtoList = new ArrayList<>();
        //定义班组合格率外层集合
//        List arraylist1 = new ArrayList<>();
        //根据线别查询近7天的品质检验单班组
        List<QualityGroupDto> list = qualityInspectionDocumentMapper.getGroupCodeList(lineCode);
//        List<String> list1=null;
//        List<String> grouplist2=null;
//        String resultA = "";
//        String resultB = "";
        //班组集合
//        List groupList = new ArrayList<>();
        for (QualityGroupDto qualityGroupDto : list) {
//            list1 = new ArrayList<String>();
//
//            grouplist2 = new ArrayList<String>();
            //获取班组名称

            GroupYieldDto groupYieldDto = new GroupYieldDto();
            String groupCode = qualityGroupDto.getGroupCode();
            AjaxResult dataByGroupCode = feignProductionService.getDataByGroupCode(groupCode);
            GroupDataDto data = JSON.parseObject(JSON.toJSONString(dataByGroupCode.get("data")), GroupDataDto.class);
            groupYieldDto.setGroupName(data.getGroupName());

            List<String> objects = new ArrayList<>();
            for (String s : arrayList) {
                //查询当前班次合格的数量和送检总数量
                YieldCountDto yieldCountDto = qualityInspectionDocumentMapper.selectYield(s, qualityGroupDto.getGroupCode());
                //当前班次合格数量
                int qualifiedNum = yieldCountDto.getQualifiedNum();
                //当前班次的送检总数量
                int checkNum = yieldCountDto.getCheckNum();
                if (checkNum != 0) {
                    BigDecimal divide = new BigDecimal(String.valueOf(qualifiedNum)).divide(new BigDecimal(String.valueOf(checkNum)), RoundingMode.CEILING);
                    objects.add(divide.toString());
                } else {
                    objects.add("0");
                }

//                Long numberA = yieldCountDto.getNumberA();
//                //当前班次送检总数量
//                Long numberB = yieldCountDto.getNumberB();
//                BigDecimal currentCountA = new BigDecimal(numberB+"");
//                BigDecimal add = new BigDecimal(numberB+"");
//
//                if (add.equals(BigDecimal.ZERO)) {
//                    resultA = "0.00";
//                } else {
//                    BigDecimal divide = currentCountA.divide(add, 2, BigDecimal.ROUND_HALF_UP);
//                    //合格率
//                    resultA = divide.multiply(new BigDecimal(100)).toString();
//                }
//                list1.add(resultA);
//                grouplist2.add(qualityGroupDto.getGroupCode());
            }
            groupYieldDto.setYieldList(objects);
//            arraylist1.add(list1);
//            groupList.add(grouplist2);
            groupYieldDtoList.add(groupYieldDto);
        }
        yieldDto.setList(groupYieldDtoList);
//        yieldDto.setDateList(arrayList);
//         yieldDto.setList(arraylist1);
//        yieldDto.setGroupList(groupList);
        return yieldDto;
    }

    /**
     * 根据批次号查询品质检验单(fegin调用)
     *
     * @param batchNumber
     * @return
     */
    @Override
    public QualityInspectionDocumentDto getDocumentByBatchNumber(String batchNumber, String degreasDocumentNumber) {
        //获取该批次下的已完成的检验单据
        QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda()
                .eq(QualityInspectionDocument::getBatchNo, batchNumber)
                .eq(QualityInspectionDocument::getAssociatedNo, degreasDocumentNumber)
                .eq(QualityInspectionDocument::getStatus, 7));
        if (qualityInspectionDocument != null) {
            QualityInspectionDocumentDto qualityInspectionDocumentDto = new QualityInspectionDocumentDto();
            BeanUtils.copyProperties(qualityInspectionDocument, qualityInspectionDocumentDto);
            qualityInspectionDocumentDto.setJudgmentGrade(String.valueOf(qualityInspectionDocument.getJudgmentGrade()));
            qualityInspectionDocumentDto.setInspectionResults(String.valueOf(qualityInspectionDocument.getInspectionResults()));
            qualityInspectionDocumentDto.setStatus(String.valueOf(qualityInspectionDocument.getStatus()));


            return qualityInspectionDocumentDto;
        }
        return new QualityInspectionDocumentDto();
    }


    /**
     * 修改品质检验单数据状态（fegin调用）
     *
     * @param updateQualityStatusVo
     * @return
     */
    @Override
    public boolean updateQualityInspectionDocument(UpdateQualityStatusVo updateQualityStatusVo) {
        List<QualityInspectionDocument> qualityInspectionDocuments = qualityInspectionDocumentMapper.selectList(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getAssociatedNo, updateQualityStatusVo.getAssociatedNo()));
        if (qualityInspectionDocuments.size() > 0) {
            for (QualityInspectionDocument entity : qualityInspectionDocuments) {
                entity.setStatus(updateQualityStatusVo.getStatus());
            }
        }
        return updateBatchById(qualityInspectionDocuments);
    }

    /**
     * 生产看板-本月品质不良分布
     *
     * @param lineCode
     * @return
     */
    @Override
    public List<BadMonthDto> getBadMonth(String lineCode) {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        List<BadMonthDto> list = qualityInspectionDocumentMapper.getBadMonth(month);
        return list;
    }
}
